package com.jtech.together.mvp.presenter;

import android.content.Context;
import android.os.Bundle;

import com.jtech.together.manager.UserManager;
import com.jtech.together.model.UserModel;
import com.jtech.together.mvp.contract.LoginContract;
import com.jtech.together.util.BmobUtil;

import cn.bmob.newim.BmobIM;
import cn.bmob.newim.listener.ConnectListener;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.LogInListener;

/**
 * 登录页面
 * Created by wuxubaiyang on 2017/5/10.
 */
public class LoginPresenter implements LoginContract.Presenter {
    private Context context;
    private LoginContract.View view;

    public LoginPresenter(Context context, LoginContract.View view, Bundle bundle) {
        this.context = context;
        this.view = view;
    }

    @Override
    public void login(String userName, String password) {
        BmobUser.loginByAccount(userName, password, new LogInListener<UserModel>() {
            @Override
            public void done(UserModel userModel, BmobException e) {
                if (null != userModel) {
                    //连接到即时通讯
                    connectIM(userModel);
                } else {
                    view.loginFail(BmobUtil.getErrorMessage(e.getErrorCode()));
                }
            }
        });
    }

    /**
     * 连接到即时通讯
     *
     * @param userModel
     */
    private void connectIM(final UserModel userModel) {
        BmobIM.connect(userModel.getObjectId(), new ConnectListener() {
            @Override
            public void done(String s, BmobException e) {
                if (null == e) {
                    view.loginSuccess(userModel);
                    //更新本地即时通讯的用户表
                    UserManager.updateIMUserInfo(userModel);
                } else {
                    view.loginFail(BmobUtil.getErrorMessage(e.getErrorCode()));
                }
            }
        });
    }
}